package de.velvettear.squirrel.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import android.os.AsyncTask;
import android.util.Log;

public class FTPHelper {
		
	public static void uploadFile(de.velvettear.squirrel.kernel.File upload, String directoryPath) {
		uploadFile(upload, directoryPath, null, false);
	}
	
	public static void uploadFile(de.velvettear.squirrel.kernel.File upload, String directoryPath, String copyName, boolean override) {
		final File file = upload.m_cFile;
		final String copy = copyName;
		final String dir = directoryPath;
		final boolean replace = override;
		
		AsyncTask<Void, Void, File> uploadTask = new AsyncTask<Void, Void, File>() {

			@Override
			protected File doInBackground(Void... params) {
				try {
					FTPClient client = new FTPClient();
					client.connect("velvettear.no-ip.org");
					
					if (!client.login("securitycam", "securitycam")) {
						client.logout();
						client.disconnect();
					}
					
					int reply = client.getReplyCode();
					if (!FTPReply.isPositiveCompletion(reply)) {
						client.logout();
						client.disconnect();
					}
					
					client.enterLocalPassiveMode();
					client.setFileType(FTP.BINARY_FILE_TYPE);
																				
					if (!directoryIsExisting(client, dir)) {
						return null;
					}
					
					if (fileIsExisting(client, file.getName())) {
						if (replace) {
							client.deleteFile(file.getName());
						} else {
							return null;
						}
					}
										
					String filePath = client.printWorkingDirectory() + File.separator + file.getName();
										
					InputStream input = new FileInputStream(file);
					client.storeFile(filePath, input);
					
					if (copy != null) {						
						if (fileIsExisting(client, copy)) {
							if (replace) {
								client.deleteFile(copy);
							} else {
								return null;
							}
						}
											
						filePath = client.printWorkingDirectory() + File.separator + copy;
											
						input = new FileInputStream(file);
						client.storeFile(filePath, input);
						
						input.close();
					}
																			
					client.logout();
					client.disconnect();
				} catch (Exception e) {
					if (e.getMessage() != null) {
						Log.e("uploadFile()", e.getMessage());
					}
				}	
				
				return file;
			}
			
			@Override
			protected void onPostExecute(File ret) {		
				if (ret != null && ret.exists()) {
					ret.delete();
				}
			}
			
		};
		
		uploadTask.execute();
	}
	
	private static boolean fileIsExisting(FTPClient client, String fileName) {
		boolean fileExisting = false;
		
		try {
			String currentDirectory = client.printWorkingDirectory();
			FTPFile[] files = client.listFiles();
			for (FTPFile file : files ) {
				if (file.getName().equals(fileName)) {
					fileExisting = true;
					continue;
				}
			}
		} catch (Exception e) {
			if (e.getMessage() != null) {
				Log.e("fileIsExisting()", e.getMessage());
			}
		}
		
		return fileExisting;
	}
	
	private static boolean directoryIsExisting(FTPClient client, String directoryPath) {
		boolean directoryExisting = false;
		
		try {
			String currentDirectory = client.printWorkingDirectory();
			String[] directoryStructure = directoryPath.split(File.separator);			
			for (String dir : directoryStructure) {
				if (dir.trim().length() > 0) {
					FTPFile[] directories = client.listDirectories();
					for (FTPFile subdirectory : directories) {
						if (subdirectory.getName().equals(dir)) {
							currentDirectory += dir + File.separator;
							client.changeWorkingDirectory(currentDirectory);
							continue;
						} 
					}					
				}
			}
	
			if (!directoryPath.endsWith(File.separator)) {
				directoryPath += File.separator;
			}
			
			if (currentDirectory.equals(directoryPath)) {
				directoryExisting = true;
			}
		} catch (Exception e) {
			if (e.getMessage() != null) {
				Log.e("directoryIsExisting()", e.getMessage());
			}
		}
		
		return directoryExisting;
	}
	
}
